package com.globalwave.report.template.excel;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExcelTemplate {

	private String name_ ;
	private HSSFWorkbook workbook ;
	private HSSFSheet sheet ;
	
	public ExcelTemplate(String name_) {
		this.name_ = name_ ;
	}
		
	public void load() throws Exception {
		
		InputStream is = this.getClass().getClassLoader().getResourceAsStream(name_) ; 
		
		workbook = new HSSFWorkbook(is);
		
		is.close() ;
		
		if (workbook == null) {
			throw new Exception("Workbook can't be found") ;
		}
		
		sheet = workbook.getSheet("Template") ;

		if (sheet == null) {
			sheet = workbook.getSheetAt(0);
		}
		
		if (sheet == null) {
			throw new Exception("Template(Sheet) can't be found") ;
		}
	}
	
	public void compile(Map<String, Object> context) throws Exception {
		
		this.context = context ;
		
		int lastRowNum = sheet.getLastRowNum() ;
		
		for (int rowIndex = 0 ; rowIndex <= lastRowNum ; rowIndex ++) {
			HSSFRow _row = sheet.getRow(rowIndex) ;
			
			if (_row == null) {
				continue ;
			}
			
			Row row = new Row(_row, this) ;
			
			row.precompile() ;
			row.compile() ;
			
			if (row.getListSize() != 0) {
				rowIndex += row.getListSize() - 1; 
				lastRowNum = sheet.getLastRowNum() ;
			}
			/*
			int lastCellNum = row.getLastCellNum() ;
			for (int cellIndex = 0 ; cellIndex <= lastCellNum ; cellIndex ++) {
				System.out.println(row.getCell(cellIndex));	
			}*/
		}
	}
	
	public void saveTo(OutputStream stream) throws Exception {
		this.workbook.write(stream) ;
		stream.close();
	}
	
	private Map<String, Object> context = null;
	
	public HSSFSheet getSheet() {
		return sheet;
	}
	
	public Map<String, Object> getContext() {
		return context;
	}
}
